package com.lhkj.ct.meta.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lhkj.ct.base.constants.SystemConstants;
import com.lhkj.ct.base.enums.DeleteStatus;
import com.lhkj.ct.base.enums.GlobalStatus;
import com.lhkj.ct.base.enums.ReturnStatus;
import com.lhkj.ct.base.exception.BusinessException;
import com.lhkj.ct.base.model.Option;
import com.lhkj.ct.base.mybatis.extension.service.impl.IServiceImpl;
import com.lhkj.ct.base.utils.OptionUtil;
import com.lhkj.ct.base.utils.TreeUtil;
import com.lhkj.ct.meta.admin.mapper.SysDeptMapper;
import com.lhkj.ct.meta.admin.model.entity.TblDepartment;
import com.lhkj.ct.meta.admin.model.vo.DepartmentVo;
import com.lhkj.ct.meta.admin.service.SysDeptService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 科室表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2023-08-31
 */
@Service
public class SysDeptServiceImpl extends IServiceImpl<SysDeptMapper, TblDepartment> implements SysDeptService {

    @Override
    public String saveDept(TblDepartment entity) {
        // 部门路径
        String treePath = generateDeptTreePath(entity.getParentId());
        entity.setTreePath(treePath);
        // 保存部门并返回部门ID
        this.insert(entity);
        return entity.getId();
    }

    @Override
    public String updateDept(TblDepartment entity) {
        TblDepartment target = getById(entity.getId());
        if (null == target) {
            throw new BusinessException(ReturnStatus.SC_BAD_REQUEST, "部门不存在！");
        }
        // 部门路径
        String treePath = generateDeptTreePath(entity.getParentId());
        entity.setTreePath(treePath);
        // 保存部门并返回部门ID
        this.updateById(entity);
        return entity.getId();
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<DepartmentVo> listDepartments(TblDepartment department) {
        // 查询数据
        List<DepartmentVo> deptList = this.getBaseMapper().listDepartments(department);
        if (deptList.isEmpty()) {
            return new ArrayList<>();
        }
        return TreeUtil.builderTree(deptList);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<Option<String>> listOptions(String organId) {
        List<TblDepartment> deptList = this.getBaseMapper().selectList(new LambdaQueryWrapper<TblDepartment>()
                .select(TblDepartment::getId, TblDepartment::getParentId, TblDepartment::getDeptName)
                .eq(TblDepartment::getStatus, GlobalStatus.NORMAL.getValue())
                .eq(StringUtils.isNotBlank(organId), TblDepartment::getOrganId, organId)
                .orderByAsc(TblDepartment::getSort)
        );
        return OptionUtil.buildTreeOption(deptList, TblDepartment::getDeptName);
    }

    @Override
    public int removeByIds(Collection<? extends Serializable> idList) {
//        for (Serializable id : idList) {
//            Asserts.assertFalse(hasChildByDeptId(id), "存在下级部门,不允许删除");
//            Asserts.assertFalse(checkDeptExistUser(id), "部门存在用户,不允许删除");
//        }
        return getBaseMapper().deleteBatchIds(idList);
    }

    @Override
    public boolean hasChildByDeptId(Serializable deptId) {
        Long count = this.getBaseMapper().selectCount(new LambdaQueryWrapper<TblDepartment>()
                .select(TblDepartment::getId)
                .eq(TblDepartment::getParentId, deptId)
                .eq(TblDepartment::getDelFlag, DeleteStatus.NORMAL));
        return count > 0;
    }

    @Override
    public boolean checkDeptExistUser(Serializable deptId) {
        return this.getBaseMapper().checkDeptExistUser((String) deptId) > 0;
    }

    /**
     * 部门路径生成
     *
     * @param parentId 父ID
     * @return 父节点路径以英文逗号(, )分割，eg: 1,2,3
     */
    private String generateDeptTreePath(String parentId) {
        String treePath = null;
        if (SystemConstants.ROOT_NODE_ID.equals(parentId)) {
            treePath = parentId;
        } else {
            TblDepartment parent = this.getById(parentId);
            if (parent != null) {
                treePath = parent.getTreePath() + "," + parent.getId();
            }
        }
        return treePath;
    }

}
